<template>
  <layout-content header="Pods">
    <div style="float: left">
      <el-button
        v-has-permissions="{
          scope: 'namespace',
          apiGroup: '',
          resource: 'pods',
          verb: 'create'
        }"
        type="primary"
        size="small"
        @click="onShouldCreate"
      >
        YAML
      </el-button>
      <el-button
        v-has-permissions="{
          scope: 'namespace',
          apiGroup: '',
          resource: 'pods',
          verb: 'list'
        }"
        type="primary"
        size="small"
        @click="onShouldTop"
      >
        Top
      </el-button>
      <el-button
        v-has-permissions="{
          scope: 'namespace',
          apiGroup: '',
          resource: 'pods',
          verb: 'delete'
        }"
        type="primary"
        size="small"
        :disabled="selections.length === 0"
        @click="onShouldDelete()"
      >
        {{ $t("commons.button.delete") }}
      </el-button>
      <el-button
        type="primary"
        size="small"
        icon="el-icon-download"
        @click="exportToXlsx()"
      >
        {{ $t("commons.button.export") }}
      </el-button>
    </div>
    <complex-table
      v-model:selects="selections"
      v-loading="uiState.loading"
      :data="srcList"
      :pagination-config="query.paginationConfig"
      :search-config="query.searchConfig"
      table-layout="auto"
      @search="reloadResourceList"
      @sort-change="onHandleSortSrcList"
    >
      <el-table-column type="selection" fix />
      <el-table-column
        :label="$t('commons.table.name')"
        prop="name"
        min-width="80"
        show-overflow-tooltip
        fix
        sortable="name"
      >
        <template #default="{ row }">
          <el-button link type="primary" @click="onShouldDetails(row)">
            {{ row.metadata.name }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('business.namespace.namespace')"
        min-width="45"
        prop="metadata.namespace"
        sortable="namespace"
      />
      <el-table-column
        :label="$t('commons.table.status')"
        min-width="30"
        sortable="status_phase"
        prop="status_phase"
      >
        <template #default="{ row }">
          <div v-if="row.status.phase === 'Running'">
            <el-tag type="success">
              {{ $t("commons.status.Running") }}
            </el-tag>
          </div>
          <div v-if="row.status.phase === 'Failed'">
            <el-tag type="danger">
              {{ $t("commons.status.Failed") }}
            </el-tag>
          </div>
          <div v-if="row.status.phase === 'Pending'">
            <el-tag type="warning">
              {{ $t("commons.status.Pending") }}
            </el-tag>
          </div>
          <div v-if="row.status.phase === 'Succeeded'">
            <el-tag type="warning">
              {{ $t("commons.status.Succeeded") }}
            </el-tag>
          </div>
          <div v-if="row.status.phase === 'Unknown'">
            <el-tag type="info">
              {{ $t("commons.status.Unknown") }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('commons.table.ready')"
        min-width="30"
        prop="pod_status"
        sortable="pod_status"
      >
        <template #default="{ row }">
          {{ getPodStatus(row) }}
        </template>
      </el-table-column>
      <el-table-column
        label="IP"
        min-width="40"
        prop="status.podIP"
        sortable="podIP"
      />
      <el-table-column
        :label="$t('business.cluster.nodes')"
        min-width="45"
        show-overflow-tooltip
        prop="status.hostIP"
        sortable="nodeName"
      />
      <el-table-column
        :label="$t('commons.table.created_time')"
        show-overflow-tooltip
        min-width="35"
        prop="creationTimestamp"
        fix
        sortable="creationTimestamp"
      >
        <template #default="{ row }">
          {{ getAge(row.metadata.creationTimestamp) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('business.pod.restart_count')"
        show-overflow-tooltip
        min-width="35"
        fix
        sortable="restart_count"
        prop="restart_count"
      >
        <template #default="{ row }">
          <span>{{ getPodRestartTimes(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('commons.table.action')">
        <template #default="{ row }">
          <el-button
            v-has-permissions="{
              scope: 'namespace',
              apiGroup: '',
              resource: 'pods',
              verb: 'update'
            }"
            size="small"
            icon="Edit"
            @click="onShouldEdit(row)"
          />
          <!-- <el-dropdown
            :hide-on-click="false"
            trigger="click"
            @command="cmd => onHandlePodAction(row, cmd)"
          >
            <el-button icon="More" size="small" />
            <template #dropdown>
              <el-dropdown-menu>
                <div v-if="(row?.spec?.containers?.length ?? 0) > 1">
                  <el-popover placement="left" trigger="hover">
                    <div v-for="(c, idx) in row.spec.containers" :key="idx">
                      <el-button
                        :disabled="!checkExecPermissions()"
                        link
                        @click="onShouldTerminal(row, c)"
                      >
                        {{ c.metadata.name }}
                      </el-button>
                    </div>
                    <template #reference>
                      <el-dropdown-item
                        :disabled="!checkExecPermissions()"
                        icon="Box"
                        command="terminal"
                      >
                        {{ $t("commons.button.terminal") }}
                        <el-icon><ArrowRight /></el-icon>
                      </el-dropdown-item>
                    </template>
                  </el-popover>
                  <el-popover placement="left" trigger="hover">
                    <div
                      v-for="c in row.spec?.containers"
                      :key="c.metadata.name"
                    >
                      <el-button
                        :disabled="!checkLogPermissions()"
                        link
                        @click="onShouldLogs(row, c)"
                      >
                        {{ c.metadata.name }}
                      </el-button>
                    </div>
                    <template #reference>
                      <el-dropdown-item
                        :disabled="!checkLogPermissions()"
                        icon="Notebook"
                        command="logs"
                      >
                        {{ $t("commons.button.logs") }}
                        <el-icon><ArrowRight /></el-icon>
                      </el-dropdown-item>
                    </template>
                  </el-popover>
                  <el-popover placement="left" trigger="hover">
                    <div
                      v-for="c of row.spec?.containers"
                      :key="c.metadata.name"
                    >
                      <el-button
                        :disabled="!checkExecPermissions()"
                        link
                        @click="onShouldOpenPodFiles(row, c)"
                      >
                        {{ c.metadata.name }}
                      </el-button>
                    </div>
                    <template #reference>
                      <el-dropdown-item icon="Files" command="files">
                        {{ $t("business.pod.pod_file") }}
                        <el-icon><ArrowRight /></el-icon>
                      </el-dropdown-item>
                    </template>
                  </el-popover>
                </div>
                <div v-else-if="(row?.spec?.containers?.length ?? 0) == 1">
                  <el-dropdown-item
                    :disabled="!checkExecPermissions()"
                    icon="Document"
                    command="terminal"
                  >
                    {{ $t("commons.button.terminal") }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    :disabled="!checkLogPermissions()"
                    icon="Tickets"
                    command="logs"
                    >{{ $t("commons.button.logs") }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    :disabled="!checkExecPermissions()"
                    icon="Files"
                    command="files"
                    >{{ $t("business.pod.pod_file") }}
                  </el-dropdown-item>
                </div>
                <el-dropdown-item icon="Download" command="download">
                  {{ $t("commons.button.download_yaml") }}
                </el-dropdown-item>
                <el-dropdown-item
                  icon="Delete"
                  :disabled="!onCheckPermissions()"
                  command="delete"
                >
                  {{ $t("commons.button.delete") }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown> -->
        </template>
      </el-table-column>
      <el-table-column type="expand">
        <template #default="{ row }">
          <div class="w-full flex flex-col items-start text-left pl-14">
            <span class="mb-2 font-bold">Containers</span>
            <el-space wrap>
              <ContainerSimpleCard
                v-for="c in row.spec?.containers"
                :key="c.name"
                :pod="row"
                :container="c"
                :status="
                  row.status?.containerStatuses?.find(c => c.name == c.name)
                "
                @handle-command="
                  (cmd, _pod, _container) =>
                    onHandlePodAction(_pod, cmd, _container)
                "
              />
            </el-space>
          </div>
        </template>
      </el-table-column>
    </complex-table>
  </layout-content>
</template>

<script setup lang="ts">
import LayoutContent from "@/views/domain/kubeHud/views/components/layout/LayoutContent.vue";
import ComplexTable from "@/views/domain/kubeHud/views/components/complex-table/index.vue";
import writeXlsxFile from "write-excel-file";
import { useI18n } from "vue-i18n";
import { Container, Pod, useK8SApi } from "@/views/domain/kubeHud/api/k8s";
import {
  useBaseCRUDProvider,
  useBaseCRUDRoute
} from "@/views/domain/kubeHud/api/provider/baseListProvider";
import { KRoutePod } from "@/views/domain/kubeHud/router";
import { getAge } from "@/views/domain/kubeHud/utils";
import { checkPermissions } from "@/views/domain/kubeHud/utils/permission";
import ContainerSimpleCard from "./widgets/ContainerSimpleCard.vue";
// import { downloadYaml } from "@/utils/actions";
// import { checkPermissions } from "@/utils/permission";
// import { cpuUnitConvert, memoryUnitConvert } from "@/utils/unitConvert";
// import { listPodMetrics } from "@/api/apis";
// import {
//   listWorkLoads,
//   deleteWorkLoad,
//   getWorkLoadByName
// } from "@/api/workloads";

const { t } = useI18n();
const { podRepo } = useK8SApi();
type Prop = {};
const props = withDefaults(defineProps<Prop>(), {});

const onCheckPermissions = () => {
  return checkPermissions({
    scope: "namespace",
    apiGroup: "",
    resource: "pods",
    verb: "delete"
  });
};
const checkExecPermissions = () => {
  return checkPermissions({
    scope: "namespace",
    apiGroup: "",
    resource: "pods/exec",
    verb: "create"
  });
};
const checkLogPermissions = () => {
  return checkPermissions({
    scope: "namespace",
    apiGroup: "",
    resource: "pods/log",
    verb: "get"
  });
};

const {
  query,
  selections,
  srcList,
  router,
  downloadSourceAsYaml,
  confirmDelete,
  uiState,
  reloadResourceList
} = useBaseCRUDProvider({
  request: {
    getDetailsReq: podRepo.getPodDetail,
    getListReq: podRepo.getPodList,
    deleteReq: podRepo.deletePod,
    updateReq: podRepo.updatePod,
    createReq: podRepo.createPod
  }
});

const { pushTo } = useBaseCRUDRoute({ router });

const getPodStatus = (pod: Pod) => {
  if (pod.status.containerStatuses) {
    const readyNum = pod.status.containerStatuses.filter(p => p.ready).length;
    return `${readyNum}/${pod.status.containerStatuses.length}`;
  }
};

const getPodRestartTimes = (pod: Pod) => {
  let times = 0;
  if (pod.status.containerStatuses) {
    pod.status.containerStatuses.forEach(p => {
      times += p.restartCount;
    });
  }
  return times;
};

const onHandleSortSrcList = (arg: any) => {};

const onShouldCreate = () => {
  pushTo(KRoutePod.Create);
};

const onShouldTop = () => {
  pushTo(KRoutePod.Top);
};

const onShouldEdit = (row: Pod) => {
  pushTo(KRoutePod.Edit, {
    name: row.metadata.name,
    namespace: row.metadata.namespace
  });
};

const onShouldDelete = (row?: Pod) => {
  confirmDelete(row);
};

const onShouldDetails = (row: Pod) => {
  pushTo(KRoutePod.Details, {
    name: row.metadata.name,
    namespace: row.metadata.namespace
  });
};

const onShouldDownload = (row: Pod) => {
  downloadSourceAsYaml(row);
};

const onShouldExec = (row: Pod) => {
  pushTo("terminal", {
    name: row.metadata.name,
    namespace: row.metadata.namespace
  });
};
const onShouldTerminal = (row: Pod, container: Container) => {
  pushTo("terminal", {
    name: row.metadata.name,
    namespace: row.metadata.namespace
  });
};

const onShouldLogs = (row: Pod, container: Container) => {};

const onShouldOpenPodFiles = (row: Pod, container: Container) => {};
const onHandlePodAction = (
  row: Pod,
  command: string,
  container?: Container
) => {
  console.log("Handle pod Action: ", row, command);
  switch (command) {
    case "download":
      downloadSourceAsYaml(row);
      break;
    case "edit":
      onShouldEdit(row);
      break;
    case "delete":
      onShouldDelete(row);
      break;
    case "files":
      onShouldOpenPodFiles(row, container);
      break;
    case "terminal":
      onShouldExec(row);
      break;
    case "logs":
      onShouldLogs(row, container);
      break;
  }
};
const exportToXlsx = () => {};
</script>
